package com.jy.rhin.infra.repo.notfication.message.po;


import com.alibaba.fastjson.JSON;
import com.jy.rhin.infra.repo.notfication.message.EReceiveLogType;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.sql.Timestamp;

@Data
@NoArgsConstructor
public class ReceiveMessageLogPo {

    public static final String TABLE_NAME = "t_receive_message_log";

    public static final String SCRIPT_INSERT = "INSERT INTO " + TABLE_NAME + " (id, type, receive_time, complete_time, message, error_msg, md5, queue) VALUES (?,?,?,?,?,?,?,?)";
    public static final String SCRIPT_EXIST_MD5 = "select id from t_receive_message_log where md5 = ? limit 1";

    @Getter
    public enum DdlReceiveMessasgeLog{
        CREATE("CREATE","create table " + TABLE_NAME + "\n" +
                "(\n" +
                "    id            bigint      not null\n" +
                "        primary key,\n" +
                "    type          varchar(10) not null comment '日志等级',\n" +
                "    receive_time  datetime   not null comment '接收时间',\n" +
                "    complete_time datetime   not null comment '完成时间',\n" +
                "    error_msg     text        null comment '错误信息',\n" +
                "    message       json        not null comment '消息体',\n" +
                "    md5           varchar(32) not null comment '消息体MD5',\n" +
                "    constraint t_receive_message_log_md5_uindex\n" +
                "        unique (md5)\n" +
                ")\n" +
                "    comment '接收消息日志';")
        , FIELD_EXTENSION("extension", "alter table t_receive_message_log\n" +
                "\tadd column extension json not null;")
        ,INDEX_RECEIVE_TIME("t_receive_message_log_receive_time_index", "create index t_receive_message_log_receive_time_index\n" +
                "\t on t_receive_message_log (receive_time desc);")
        ;

        DdlReceiveMessasgeLog(String key, String sql) {
            this.key = key;
            this.sql = sql;
        }

        String key;
        String sql;
    }

    Long id;
    /**日志类型*/
    EReceiveLogType type;
    /**接收时间*/
    Timestamp receiveTime;
    /**完成时间*/
    Timestamp completeTime;
    /**错误信息*/
    String errorMsg;
    /**消息内容*/
    String message;
    /**消息内容MD5*/
    String md5;
    /**扩展信息*/
    Extension extension ;

    public String getExtension() {
        return JSON.toJSONString(this.extension);
    }

    public void addExtension(String routingKey, String queue, String messageId) {
        this.extension = new Extension(routingKey, queue, messageId);
    }

    @Data
    @NoArgsConstructor
    class Extension{
        public Extension(String routingKey, String queue, String messageId) {
            this.routingKey = routingKey;
            this.queue = queue;
            this.messageId = messageId;
        }

        String routingKey;
        String queue;
        String messageId;
    }
}
